package cn.tjad.tjad2;

import android.Manifest;
import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.Log;

import com.hjy.http.download.DownloadManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import cn.tjad.tjad2.consts.TjadConsts;
import cn.tjad.tjad2.consts.UrlConsts;
import cn.tjad.tjad2.utils.FileHelper;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.utils.ZipUtils;
import pub.devrel.easypermissions.EasyPermissions;

public class AppStartService extends IntentService {

    private static final String TAG = "AppStartService";

    public AppStartService() {
        this(TAG);
    }

    public AppStartService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            updateHtmlFileIfNeeded();
            updateHtmlFiles();
        }
    }

    private void updateHtmlFileIfNeeded() {
        if (Tools.isAppUpdate()) {
            Log.d(TAG, "app升级,更新apphtml");
            File file = new File(TjadConsts.WEB);
            if (file.exists()) {
                FileHelper.deleteFile(TjadConsts.WEB);
            }
            unzipHtmlFileIfNeeded();
            Tools.recordAppVersionCode();
        }
    }

    private void unzipHtmlFileIfNeeded() {
        File webDir = new File(TjadConsts.WEB);
        if (!webDir.exists()) {
            webDir.mkdirs();
            Log.d(TAG, "路径" + TjadConsts.WEB + "不存在， 创建成功！");
        }
        String client = TjadConsts.APPHTML + "/client.html";
        File clientFile = new File(client);
        if (!clientFile.exists()) {
            Log.d(TAG, "文件" + client + "不存在");
            File tempDir = new File(TjadConsts.TEMP);
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
            String tempFileStr = TjadConsts.TEMP + "/apphtml.zip";
            File tempFile = new File(tempFileStr);
            if (tempFile.exists()) {
                tempFile.delete();
            }
            InputStream is = getResources().openRawResource(R.raw.apphtml);
            try {
                FileOutputStream fos = new FileOutputStream(tempFile);
                byte[] buffer = new byte[is.available()];
                int length = 0;
                while ((length = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, length);
                }
                fos.flush();
                fos.close();
                is.close();
                Log.d(TAG, "文件apphtml.zip复制到" + tempFile);
                ZipUtils.UnZipFolder(tempFileStr, TjadConsts.APPHTML);
                Log.d(TAG, "文件" + tempFileStr + "解压到" + TjadConsts.APPHTML);
                tempFile.delete();
                Log.d(TAG, "删除文件" + tempFileStr);
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "操作异常" + e.getMessage());
                Tools.showToast("离线文件解压异常");
            }
        }
    }

    private void updateHtmlFiles() {
        for (String url : UrlConsts.RES_FILE_URL) {
            File tempDir = new File(TjadConsts.TEMP);
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
            String fileName = Uri.parse(url).getLastPathSegment();
            fileName.replace("/", "");
            String temp = TjadConsts.TEMP + "/" + fileName;
            Log.d(TAG, "准备下载文件" + fileName + "到" + temp);
            File tempFile = new File(temp);
            if (tempFile.exists()) {
                tempFile.delete();
                Log.d(TAG, "文件" + temp + "已存在， 删除");
            }
            File file = DownloadManager.getInstance().downloadFileSync(tempFile, url, url);
            if (file != null) {
                Log.d(TAG, "文件下载完成" + file.getPath());
            }
            String dest = TjadConsts.APPHTML + "/client/forge/" + fileName;
            File destFile = new File(dest);
            if (destFile.exists()) {
                destFile.delete();
                Log.d(TAG, "目标文件" + dest +"已存在，删除");
            }
            try {
                FileHelper.copyFile(tempFile, destFile);
                Log.d(TAG, "复制文件" + tempFile + "到" + destFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            FileHelper.deleteFile(temp);
            Log.d(TAG, "删除文件" + temp);
        }
    }
}
